<template>
<view class="page2 download">
    <!-- <Tabs :tabs="tabs" @change="changeTab"/> -->
    <nut-tabs v-model="curentTab"  title-scroll title-gutter="5" :auto-height="true" @change="changeTab" v-if="tabs.length>0">
        <nut-tabpane :title="item.name" v-for="(item, index) in tabs" :key="item.id" :pane-key="item.id">
            <view class="videoList" v-if="curentTab===item.id">
                <view class="videoBox" v-for="file in item.media" @click="selecthandle(curentTab, file, index)" :key="file.id">
                    <cdn-img class="video" :src="file.upload.full_path+'?vframe/jpg/offset/1/w/71'" mode="aspectFill" :lazyLoad="true"/>
                    <nut-icon name="play-start" color="#fff" class="playIcon" @click.stop="playVideo(file.upload.full_path)"></nut-icon>
                    <template v-if="(selectArr[curentTab]&&selectArr[curentTab] === file.id)">
                        <view class="selectBox"></view>
                        <nut-icon name="checked" class="checked" color="#2A5CFF"></nut-icon>
                    </template>
                </view>
            </view>
        </nut-tabpane>
    </nut-tabs>
    <!-- <video src="" :controls="false" class="video"></video> -->
    <view class="fixedBottom">
        <view class="redTip">*每个分类下只能选择一个素材下载，当前需要分别选择{{ tabs.length }}个分类素材</view>
        <view class="btn-blue4 bot fcenter" @click="beforeDownLoad">一键批量下载（{{selectLen}} / {{tabs.length}}）</view>
    </view>
    <!-- 视频预览 -->
    <!-- <nut-overlay v-model:visible="showVideo"></nut-overlay> -->
    <nut-popup v-model:visible="showVideo" :z-index="10000">
        <video :src="video" :controls="true" class="screen" :autoplay="true" :loop="true"></video>
    </nut-popup>
    <!-- 下载进度弹窗 -->
    <nut-popup pop-class="popclass" v-model:visible="showProgress" :z-index="10000" :close-on-click-overlay="false">
        <view class="progressBox fcenter">
            <p class="progress_tit">视频下载进度</p>
            <nut-progress
                :percentage="percent"
                stroke-color="linear-gradient(270deg, rgba(18,126,255,1) 0%,rgba(32,147,255,1) 32.815625%,rgba(13,242,204,1) 100%)"
                status="active"
                :text-inside="true"
            />
        </view>
    </nut-popup>
</view>
</template>

<script setup>
// import Tabs from '@/components/Tabs'
// import { storeToRefs } from 'pinia';
import { useOrderStore } from '@/stores'
import { ref, reactive, computed } from 'vue'
import { useLoad, showToast, showModal, requestPayment } from '@tarojs/taro'
import { navigateTo } from '@/router'
import { videoList, activityDetail  } from '@/api'
import { getPhotosAlbumAuth, download } from '@/utils/downLoad'
import "./index.scss";

// const { info, tiktok } = storeToRefs(user);
const order = useOrderStore()
const tabs = ref([])
const curentTab = ref(0)
const showVideo = ref(false)
const video = ref('')
const selectArr = reactive({})
const showProgress = ref(false)
const percent = ref(0)
let source_pay_money = 0
let videoArr = []
let actid = null

const selectLen = computed(()=>{
    const arr = Object.values(selectArr).filter(item=>!!item)
    return arr.length
})

const goToSub = (url) => {
  navigateTo({ url: "/pagesub/"+url });
};

function changeTab(tab){
  const id = Number(tab.paneKey)
  curentTab.value = id
}

function playVideo(src){
    if(!src) return
    video.value = src
    showVideo.value = true
}
function selecthandle(tab, file, i){
    const index = file.id
    if(selectArr[tab] === index){
        selectArr[tab] = undefined
        videoArr[i] = undefined
    }else{
        selectArr[tab] = index
        videoArr[i] = file.upload.full_path
    }
}
// 队列
function downForque() {
    showProgress.value = true
    let promise = Promise.resolve()
    const list = videoArr.filter(item=>!!item)
    list.forEach((url, index) => {
        percent.value = 0
        promise = promise.then(() => {
            return download(url, index, list.length-1, (progress)=>{
                percent.value = progress
            },()=>{
                showProgress.value = false
                showToast({title: '下载完成', icon: 'success'});
            })
        })
    })
    return promise;
}
function startDownLoad(){
    // 获取相册权限并下载
    getPhotosAlbumAuth(downForque)
}
function confirmPay(){
    showModal({
        title: '下载须知',
        content: `当前任务所属活动开启了付费下载素材，您需要支付${source_pay_money}元素材费，您是否要继续下载`,
        success: function (res) {
            if (res.confirm) {
                openPay()
            }
        }
    })
}
function openPay(){
    // goToSub('applypay/video')
    if(!actid) return showToast({title: '活动ID不存在',icon: 'none'});
    order.CreatApplyOrder({id: actid,type: 2}).then(res=>{
        if(res&&res.config){
            requestPayment({
                ...res.config,
                success:()=> {
                    showToast({title: '支付成功开始下载', icon: 'success', duration: 2000})
                    startDownLoad()
                },
            })
        }
    })
}
function beforeDownLoad(){
    if(selectLen.value < tabs.value.length) return showToast({title: '所选素材数量不足', icon: 'none'});
    // 是否需要支付素材费用
    source_pay_money>0
        ? confirmPay()
        : startDownLoad()
}
useLoad((option)=>{
    if(option&&option.id){
        actid = option.id
        videoList(option.id).then(res=>{
            if(res.data){
                tabs.value = res.data.data
                if(tabs.value.length>0){
                    curentTab.value = tabs.value[0].id
                }
            }
        })
        // 从活动详情获取是否需要素材付费
        activityDetail(option.id).then(res=>{
            if(res.data){
                source_pay_money = res.data.source_pay_money
            }
        })
    }
})
</script>